package com.gxa.interceptor;

import com.gxa.pojo.Admin;
import com.gxa.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * @author: 42818
 * @date: 2022/9/2 16:04
 * @Software: IntelliJ IDEA
 * @Package_Name: com.gxa.interceptor
 * @ClassName: ShiroRealm
 * @Description:
 **/

public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private AdminService service;

    /**
     * 登录的验证实现方法   认证
     *
     * @param token
     * @return AuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken token2 = (UsernamePasswordToken) token;
        String username = token2.getUsername();
        Admin admin = new Admin();
        admin.setAdminName(username);
        Admin user = service.query(admin);
        if (user == null) {
            throw new UnknownAccountException("用户名或密码有误！");
        }
        if (user.getAdminState() == 0) {
            throw new UnknownAccountException("用户名已被禁用，请联系系统管理员！");
        }

        /**
         * principals: 可以使用户名，或d登录用户的对象
         * hashedCredentials: 从数据库中获取的密码
         * credentialsSalt：密码加密的盐值
         * RealmName:  类名（ShiroRealm）
         */
        AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getAdminPassword(), null, getName());
        System.out.println(this.service);
        System.out.println("111111111111111111111111111111111111111111111111111");
        return info; //框架完成验证
    }


    /**
     * 登录的验证实现方法   授权
     *
     * @param principals
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}
